package com.utils;

import java.util.ArrayList;
import java.util.List;

import com.beifu.manager.model.Module;
import com.beifu.manager.model.Tree;

public class TreeUtils {
	
	/**
	 * 获取用户菜单列表
	 * @param moduleList
	 * @return
	 */
	public static List<Tree> module2TreeList(List<Module> moduleList){
		List<Tree> treeList = new ArrayList<Tree>();
		for(Module module : moduleList){
			if(null == module.getParentModule() || module.getParentModule() == 0){
				Tree tree = new Tree();
				tree = getTree(module);
				tree.setChildren(getSubTreeList(module.getId(),moduleList));
				treeList.add(tree);
			}
		}
		return treeList;
	}
	
	private static List<Tree> getSubTreeList(Integer moduleId,List<Module> moduleList){
		List<Tree> childTree = new ArrayList<Tree>();

		for(Module module : moduleList){
			if(null != module.getParentModule() && moduleId == module.getParentModule()){
				childTree.add(getTree(module));
			}
		}
		
		for(Tree tree:childTree){
			tree.setChildren(getSubTreeList(tree.getId().intValue(), moduleList));
		}
		
		if(childTree.size() == 0){
			return null;
		}
		return childTree;
	}
	
	private static Tree getTree(Module module){
		Tree tree = new Tree();
		tree.setId(Long.valueOf(module.getId()));
		tree.setName(module.getModuleName());
		tree.setType(Integer.valueOf(module.getModuleType()));
		tree.setIcon(module.getModuleIcon());
		tree.setDataUrl(module.getModulePath());
		return tree;
	}

	
}
